package cn.xinfei.xdecision.data.config;

import cn.xinfei.xdecision.data.thread.MdcTraceIdTaskDecorator;
import cn.xinfei.xdecision.prometheus.thread.PrometheusThreadPool;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Slf4j
@Component
public class AsyncConfig implements AsyncConfigurer {



    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(10000);
        taskExecutor.setKeepAliveSeconds(5 * 60);
        taskExecutor.setThreadNamePrefix("Async-Task-Executor-");
        taskExecutor.setTaskDecorator(new MdcTraceIdTaskDecorator(true));
        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("params = {},method = {}, 线程池执行任务发生异常",
                JSONObject.toJSONString(params),
                method.getName(),
                ex);
    }


}
